package com.neusoft.hifly.commons.lang.format;

import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;

/**
 * Title: 核心类库
 * <p>
 * Description: 字节大小格式化。例如，12345 byes = 12.1 K , 1234567 byes = 1.18 MB。
 * <p>
 * Copyright: Copyright (c) 2010 - 2011
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
public class ByteFormat extends Format {
	private static final long serialVersionUID = 7474757502208455483L;

	/**
	 * Formats a long which represent a number of bytes.
	 */
	public String format(final long bytes) {
		return this.format(new Long(bytes));
	}

	/**
	 * Formats a long which represent a number of kilobytes.
	 */
	public String formatKB(final long kilobytes) {
		return this.format(new Long(kilobytes * 1024));
	}

	/**
	 * Format the given object (must be a Long).
	 *
	 * @param obj
	 *            assumed to be the number of bytes as a Long.
	 * @param buf
	 *            the StringBuffer to append to.
	 * @param pos
	 *            position
	 * @return A formatted string representing the given bytes in more human-readable form.
	 */
	@Override
	public StringBuffer format(final Object obj, final StringBuffer buf, final FieldPosition pos) {
		if (obj instanceof Long) {
			final long numBytes = ((Long) obj).longValue();
			if (numBytes < 1024 * 1024) {
				final DecimalFormat formatter = new DecimalFormat("#,##0.0");
				buf.append(formatter.format(numBytes / 1024.0)).append(" K");
			} else {
				final DecimalFormat formatter = new DecimalFormat("#,##0.0");
				buf.append(formatter.format(numBytes / (1024.0 * 1024.0))).append(" MB");
			}
		}
		return buf;
	}

	/**
	 * In this implementation, returns null always.
	 *
	 * @param source
	 * @param pos
	 * @return returns null in this implementation.
	 */
	@Override
	public Object parseObject(final String source, final ParsePosition pos) {
		return null;
	}

	/**
	 * 测试
	 *
	 * @param args
	 *            参数
	 */
	public static void main(final String[] args) {
		//		final long bytes = 900000l;
		//		//		1.2 MB
		//		System.out.println(new ByteFormat().format(bytes));
		//		//		1,205.6 MB
		//		System.out.println(new ByteFormat().formatKB(bytes));
		//
		//		final DecimalFormat formatter = new DecimalFormat("0.0");
		//		System.out.println(formatter.format(9000000.0 / (1024.0 * 1024.0)));
	}
}